<template>
  <div class="app-container">
    <div v-if="user">
      <el-row :gutter="20">
        <el-col :span="8" :xs="24">
          <user-card :user="user" />
        </el-col>

        <el-col :span="16" :xs="24">
          <el-card>
            <el-tabs v-model="activeTab">
              <!-- <el-tab-pane label="Activity" name="activity">
                <activity />
              </el-tab-pane>-->
              <!-- <el-tab-pane label="Timeline" name="timeline">
                <timeline />
              </el-tab-pane>-->
              <el-tab-pane label="Account" name="account">
                <!-- <account :user="user" /> -->
                <el-table
                  row-key="id"
                  @row-click="rowClick"
                  :expand-row-keys="expands"
                  :data="list"
                  style="width: 100%"
                >
                  <el-table-column type="expand">
                    <template slot-scope="props">
                      <el-form
                        v-if="props.row.id == 1"
                        style="margin-left:130px"
                        label-position="left"
                        inline
                        class="table-expand"
                        :model="formName"
                        ref="nameform"
                        :rules="namerules"
                      >
                        <el-form-item prop="username">
                          <div class="changeInput">
                            <el-input
                              placeholder="新登录用户名"
                              type="username"
                              v-model="formName.username"
                              autocomplete="off"
                            ></el-input>
                          </div>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="changeUserName('nameform')">确定</el-button>
                          <el-button @click="resetNameForm('nameform')">重置</el-button>
                        </el-form-item>
                      </el-form>
                      <el-form
                        v-if="props.row.id == 2"
                        style="margin-left:130px"
                        label-position="left"
                        inline
                        class="table-expand"
                        :model="formPass"
                        ref="passform"
                        :rules="passrules"
                      >
                        <el-form-item prop="pass">
                          <div class="changeInput">
                            <el-input
                              :key="passwordType1"
                              :type="passwordType1"
                              placeholder="当前密码"
                              v-model="formPass.pass"
                              autocomplete="off"
                              name="nowpassword"
                              ref="nowpassword"
                            ></el-input>
                            <span class="show-pwd" @click="showPwd1">
                              <svg-icon
                                :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'"
                              />
                            </span>
                          </div>
                        </el-form-item>
                        <el-form-item prop="newPass">
                          <div class="changeInput">
                            <el-input
                              :key="passwordType2"
                              :type="passwordType2"
                              placeholder="新密码"
                              name="newpassword"
                              v-model="formPass.newPass"
                              autocomplete="off"
                              ref="newpassword"
                            ></el-input>
                            <span class="show-pwd" @click="showPwd2">
                              <svg-icon
                                :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'"
                              />
                            </span>
                          </div>
                        </el-form-item>
                        <el-form-item prop="checkPass">
                          <div class="changeInput">
                            <el-input
                              :key="passwordType3"
                              :type="passwordType3"
                              placeholder="确认密码"
                              name="checkpassword"
                              v-model="formPass.checkPass"
                              autocomplete="off"
                              ref="checkpassword"
                            ></el-input>
                            <span class="show-pwd" @click="showPwd3">
                              <svg-icon
                                :icon-class="passwordType3 === 'password' ? 'eye' : 'eye-open'"
                              />
                            </span>
                          </div>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="changePassword('passform')">确定</el-button>
                          <el-button @click="resetPassword('passform')">重置</el-button>
                        </el-form-item>
                      </el-form>
                      <el-form
                        v-if="props.row.id == 3"
                        style="margin-left:130px"
                        label-position="left"
                        inline
                        class="table-expand"
                        :model="formNickName"
                        ref="nicknameform"
                      >
                        <el-form-item>
                          <div class="changeInput">
                            <el-input
                              placeholder="新显示昵称"
                              type="username"
                              v-model="formNickName.nickname"
                              autocomplete="off"
                            ></el-input>
                          </div>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="changeNickName('nicknameform')">确定</el-button>
                          <el-button @click="resetNickName('nicknameform')">重置</el-button>
                        </el-form-item>
                      </el-form>
                      <el-form
                        v-if="props.row.id == 4"
                        style="margin-left:130px"
                        label-position="left"
                        inline
                        class="table-expand"
                        :model="formEmail"
                        ref="emailform"
                      >
                        <el-form-item>
                          <div class="changeInput">
                            <el-input
                              placeholder="新邮箱"
                              v-model="formEmail.email"
                              autocomplete="off"
                            ></el-input>
                          </div>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="changeEmail('emailform')">确定</el-button>
                          <el-button @click="resetEmail('emailform')">重置</el-button>
                        </el-form-item>
                      </el-form>
                      <el-form
                        v-if="props.row.id == 5"
                        style="margin-left:130px"
                        label-position="left"
                        inline
                        class="table-expand"
                        :model="formContact"
                        ref="contactform"
                      >
                        <el-form-item>
                          <div class="changeInput">
                            <el-input
                              placeholder="新联系方式"
                              v-model="formContact.phone"
                              autocomplete="off"
                            ></el-input>
                          </div>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="changePhone('contactform')">确定</el-button>
                          <el-button @click="resetPhone('contactform')">重置</el-button>
                        </el-form-item>
                      </el-form>
                    </template>
                  </el-table-column>
                  <el-table-column width="130" label="账户与安全" prop="name"></el-table-column>
                  <el-table-column prop="value"></el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import userApi from "@/api/user";
import { mapGetters } from "vuex";
import UserCard from "./components/UserCard";
// import Activity from './components/Activity'
// import Timeline from './components/Timeline'
import Account from "./components/Account";

export default {
  name: "Profile",
  components: { UserCard, Account },
  data() {
    return {
      passwordType1: "password",
      passwordType2: "password",
      passwordType3: "password",
      formName: {
        username: ""
      },
      formPass: {
        pass: "",
        newPass: "",
        checkPass: ""
      },
      formNickName: {
        nickname: ""
      },
      formEmail: {
        email: ""
      },
      formContact: {
        phone: ""
      },
      user: {},
      list: [],
      activeTab: "account",
      // 要展开的行，数值的元素是row的key值
      expands: [],
      tableData: [
        {
          id: "1",
          name: "登录用户名",
          desc: "username"
        },
        {
          id: "2",
          name: "密码",
          desc: "********"
        },
        {
          id: "3",
          name: "显示昵称",
          desc: "flypig"
          //   desc: this.user.nickname,
        },
        {
          id: "4",
          name: "邮箱",
          desc: "xxxxxxxxx@qq.com"
        },
        {
          id: "5",
          name: "电话",
          desc: "xxxxxxxxxxx"
        }
      ],
      namerules: {
        username: [
          { required: true, message: "请输入新的用户名", trigger: "blur" },
          { min: 4, max: 30, message: "长度在 3 到 30 个字符", trigger: "blur" }
        ]
      },
      passrules: {
        newPass: [
          { required: true, message: "请输入新的密码", trigger: "blur" },
          { min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur" }
        ],
        checkPass: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur" }
        ]
      },
      count: ""
    };
  },
  computed: {
    ...mapGetters([
      "userid",
      "name",
      "avatar",
      "roles",
      "nickname",
      "remark",
      "email",
      "phone"
    ])
  },
  created() {
    this.getUser();
    this.getList();
  },
  // watch: {
  //   "$store.state.user.name": function() {
  //     this.getUser();
  //     this.getList();
  //   }
  // },
  methods: {
    getUser() {
      this.user = {
        id: this.userid,
        name: this.name,
        // role: this.roles.join(' | '),
        role: this.roles,
        avatar: this.avatar,
        nickname: this.nickname,
        remark: this.remark,
        email: this.formatEmailString(this.email),
        phone: this.formatPhoneString(this.phone)
      };
    },
    // 截取替换电话字符串
    formatPhoneString(value) {
      var len = value.length;
      var num = value.substring(3, len - 4);
      return value.replace(num, "****");
    },
    // 截取替换邮箱字符串
    formatEmailString(value) {
      var len = value.length;
      var index = value.indexOf("@");
      console.log("@的位置：", index);
      var num = value.substring(5, index);
      return value.replace(num, "*******");
    },

    //在<table>里，我们已经设置row的key值设置为每行数据id：row-key="id"
    rowClick(row, event, column) {
      Array.prototype.remove = function(val) {
        let index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      if (this.expands.indexOf(row.id) < 0) {
        this.expands = [];
        this.expands.push(row.id);
      } else {
        this.expands.remove(row.id);
      }
    },
    showPwd1() {
      if (this.passwordType1 === "password") {
        this.passwordType1 = "";
      } else {
        this.passwordType1 = "password";
      }
      this.$nextTick(() => {
        this.$refs.nowpassword.focus();
      });
    },
    showPwd2() {
      if (this.passwordType2 === "password") {
        this.passwordType2 = "";
      } else {
        this.passwordType2 = "password";
      }
      this.$nextTick(() => {
        this.$refs.newpassword.focus();
      });
    },
    showPwd3() {
      if (this.passwordType3 === "password") {
        this.passwordType3 = "";
      } else {
        this.passwordType3 = "password";
      }
      this.$nextTick(() => {
        this.$refs.checkpassword.focus();
      });
    },
    getList() {
      this.list = [
        { id: 1, name: "登录用户名", value: this.name },
        { id: 2, name: "密码", value: "********" },
        { id: 3, name: "显示昵称", value: this.nickname },
        { id: 4, name: "邮箱", value: this.formatEmailString(this.email) },
        { id: 5, name: "电话", value: this.formatPhoneString(this.phone) }
      ];
    },

    changeUserName(formName) {
      var vm = this.$store;
      const pojo = {
        uName: this.formName.username,
        id: this.userid
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 判断用户名是否存在
          userApi.queryUserName(this.formName.username).then(resp => {
            if (resp.data.msg > 0) {
              // 用户名存在
              this.$message({
                message: "该用户名已存在",
                type: "warning"
              });
              return false;
            } else {
              userApi.update(pojo).then(resp => {
                if (resp.data.code == 0) {
                  // 修改成功
                  this.$message({
                    message: "修改用户名成功，请重新登录",
                    type: "success"
                  });
                  // var name = this.pojo.uName;
                  // vm.commit("user/SET_NAME", name);
                  // vm.commit("updateLoading", true);
                  //重新加载
                  // location.reload();
                  // console.log("当前用户名", this.$store.state.user.name);
                  // 重新登录
                  //延时1秒
                  const TIME_COUNT = 1;
                  0;
                  if (!this.timer) {
                    this.count = TIME_COUNT;
                    this.timer = setInterval(() => {
                      if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                      } else {
                        clearInterval(this.timer);
                        this.timer = null;
                        this.logout();
                      }
                    }, 1000);
                  }
                } else {
                  this.$message({
                    message: "修改用户名失败",
                    type: "warning"
                  });
                  return false;
                }
              });
            }
          });
        } else {
          this.$message({
            message: "修改用户名失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    // 退出登录
    async logout() {
      await this.$store.dispatch("user/logout");
      this.$router.push(`/login?redirect=${this.$route.fullPath}`);
    },

    resetNameForm(formName) {
      this.formName.username = "";
      this.$refs[formName].resetFields();
    },

    changePassword(formName) {
      // 查询是否有该用户
      this.$refs[formName].validate(valid => {
        if (valid) {
          userApi.queryUser(this.name, this.formPass.pass).then(resp => {
            if (resp.data.code == 0) {
              // 确定是该用户在操作
              if (this.formPass.newPass != this.formPass.checkPass) {
                this.$message({
                  message: "新密码与确认密码不一致，请重新输入",
                  type: "warning"
                });
                return false;
              } else {
                const pojo = {
                  uPass: this.formPass.checkPass,
                  id: this.userid
                };
                userApi.update(pojo).then(resp => {
                  if (resp.data.code == 0) {
                    // 修改成功
                    this.$message({
                      message: "修改密码成功，请重新登录",
                      type: "success"
                    });
                    // 重新登录
                    //延时1秒
                    const TIME_COUNT = 1;
                    0;
                    if (!this.timer) {
                      this.count = TIME_COUNT;
                      this.timer = setInterval(() => {
                        if (this.count > 0 && this.count <= TIME_COUNT) {
                          this.count--;
                        } else {
                          clearInterval(this.timer);
                          this.timer = null;
                          this.logout();
                        }
                      }, 1000);
                    }
                  } else {
                    this.$message({
                      message: "修改密码失败",
                      type: "warning"
                    });
                    return false;
                  }
                });
              }
            } else {
              this.$message({
                message: "密码有误，请重新输入",
                type: "warning"
              });
              return false;
            }
          });
        } else {
          this.$message({
            message: "修改密码失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    resetPassword(formName) {
      this.formPass = {
        pass: "",
        newPass: "",
        checkPass: ""
      };
      this.$refs[formName].resetFields();
    },

    changeNickName(formName) {
      // var vm = this.$store;
      const pojo = {
        uNickname: this.formNickName.nickname,
        id: this.userid
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 判断用户名是否存在
          userApi.queryNickName(this.formNickName.nickname).then(resp => {
            if (resp.data.msg > 0) {
              // 用户名存在
              this.$message({
                message: "该昵称已存在",
                type: "warning"
              });
              return false;
            } else {
              userApi.update(pojo).then(resp => {
                if (resp.data.code == 0) {
                  // 修改成功
                  this.$message({
                    message: "修改昵称成功，请重新登录",
                    type: "success"
                  });
                  // var name = this.pojo.uName;
                  // vm.commit("user/SET_NAME", name);
                  // vm.commit("updateLoading", true);
                  //重新加载
                  // location.reload();
                  // console.log("当前用户名", this.$store.state.user.name);
                  // 重新登录
                  //延时1秒
                  const TIME_COUNT = 1;
                  0;
                  if (!this.timer) {
                    this.count = TIME_COUNT;
                    this.timer = setInterval(() => {
                      if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                      } else {
                        clearInterval(this.timer);
                        this.timer = null;
                        this.logout();
                      }
                    }, 1000);
                  }
                }
              });
            }
          });
        } else {
          this.$message({
            message: "修改昵称失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    resetNickName(formName) {
      this.formNickName.nickname = "";
      this.$refs[formName].resetFields();
    },

    changeEmail(formName) {
      const pojo = {
        uEmail: this.formEmail.email,
        id: this.userid
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          userApi.update(pojo).then(resp => {
            if (resp.data.code == 0) {
              // 修改成功
              this.$message({
                message: "修改邮箱成功，请重新登录",
                type: "success"
              });
              // var name = this.pojo.uName;
              // vm.commit("user/SET_NAME", name);
              // vm.commit("updateLoading", true);
              //重新加载
              // location.reload();
              // console.log("当前用户名", this.$store.state.user.name);
              // 重新登录
              //延时1秒
              const TIME_COUNT = 1;
              0;
              if (!this.timer) {
                this.count = TIME_COUNT;
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--;
                  } else {
                    clearInterval(this.timer);
                    this.timer = null;
                    this.logout();
                  }
                }, 1000);
              }
            }
          });
        } else {
          this.$message({
            message: "修改邮箱失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    resetEmail(formName) {
      this.formEmail.email = "";
      this.$refs[formName].resetFields();
    },

    changePhone(formName) {
      const pojo = {
        uContact: this.formContact.phone,
        id: this.userid
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          userApi.update(pojo).then(resp => {
            if (resp.data.code == 0) {
              // 修改成功
              this.$message({
                message: "修改联系方式成功，请重新登录",
                type: "success"
              });
              // 重新登录
              //延时1秒
              const TIME_COUNT = 1;
              0;
              if (!this.timer) {
                this.count = TIME_COUNT;
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--;
                  } else {
                    clearInterval(this.timer);
                    this.timer = null;
                    this.logout();
                  }
                }, 1000);
              }
            }
          });
        } else {
          this.$message({
            message: "修改联系方式失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    resetPhone(formName) {
      this.formContact.phone = "";
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style>
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.changeInput {
  width: 250px;
}
/* .el-form-item {
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  color: #454545;
} */
.show-pwd {
  position: absolute;
  right: 10px;
  top: 2px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>
